import React, { useEffect, useRef } from 'react';
import style from './01.less';
export default function Proto() {
    let canvas, context, FONT_HEIGHT = 15,
        MARGIN = 35, HAND_TRUNCATION, HOUR_HAND_TRUNCATION, NUMERAL_SPACING = 20,
        RADIUS, HAND_RADIUS;
    let timer = useRef(null);

    // 最外圈的原 
    function drawCircle() {
        context.beginPath();
        context.arc(canvas.width / 2, canvas.height / 2, RADIUS, 0, Math.PI * 2, true);
        context.stroke();
    }

    function drawNumberals() {
        let numberals = [],
            angle = 0,
            numberalWidth = 0;
        numberals = [...Array.from({ length: 12 }, (v, k) => k + 1)];

        numberals.forEach((numberal) => {
            angle = Math.PI / 6 * (numberal - 3);
            numberalWidth = context.measureText(numberal).width;
            context.fillText(numberal, canvas.width / 2 + Math.cos(angle) * HAND_RADIUS - numberalWidth / 2, canvas.height / 2 + Math.sin(angle) * HAND_RADIUS + FONT_HEIGHT / 3);
        });
    }

    function drawCenter() {
        context.beginPath();
        context.arc(canvas.width / 2, canvas.height / 2, 5, 0, Math.PI * 2, true);
        context.fill();
    }

    function drawHand(loc, isHour) {
        let angle = (Math.PI * 2) * (loc / 60) - Math.PI / 2,
            handRadius = isHour ? RADIUS - HAND_TRUNCATION - HOUR_HAND_TRUNCATION : RADIUS - HAND_TRUNCATION;

        context.moveTo(canvas.width / 2, canvas.height / 2);
        context.lineTo(canvas.width / 2 + Math.cos(angle) * handRadius,
            canvas.height / 2 + Math.sin(angle) * handRadius);
        context.stroke();
    }

    function drawHands() {
        let date = new Date,
            hour = date.getHours();
        hour = hour > 12 ? hour - 12 : hour;

        drawHand(hour * 5 + (date.getMinutes() / 60) * 5, true);
        drawHand(date.getMinutes(), false);
        drawHand(date.getSeconds(), false);
    }

    function drawClock() {
        context.clearRect(0, 0, canvas.width, canvas.height);

        drawCircle();
        drawCenter();
        drawHands();
        drawNumberals();
    }

    useEffect(() => {
        canvas = document.getElementById('canvas'),
        context = canvas.getContext('2d'),
        HAND_TRUNCATION = canvas.width / 25,
        HOUR_HAND_TRUNCATION = canvas.width / 10,
        RADIUS = canvas.width / 2 - MARGIN,
        HAND_RADIUS = RADIUS + NUMERAL_SPACING;
        context.font = FONT_HEIGHT + 'px Arial';
        timer = setInterval(drawClock, 1000);
        return () => {
            clearInterval(timer);
        };
    });
    return (
        <canvas id="canvas" className={style.canvas} width="400" height="400">
        </canvas>
    );
}